Import('env', 'arch')

gen = "c_generated_code"

casadi_model = [
  f'{gen}/lat_model/lat_expl_ode_fun.c',
  f'{gen}/lat_model/lat_expl_vde_forw.c',
]

casadi_cost_y = [
  f'{gen}/lat_cost/lat_cost_y_fun.c',
  f'{gen}/lat_cost/lat_cost_y_fun_jac_ut_xt.c',
  f'{gen}/lat_cost/lat_cost_y_hess.c',
]

casadi_cost_e = [
  f'{gen}/lat_cost/lat_cost_y_e_fun.c',
  f'{gen}/lat_cost/lat_cost_y_e_fun_jac_ut_xt.c',
  f'{gen}/lat_cost/lat_cost_y_e_hess.c',
]

casadi_cost_0 = [
  f'{gen}/lat_cost/lat_cost_y_0_fun.c',
  f'{gen}/lat_cost/lat_cost_y_0_fun_jac_ut_xt.c',
  f'{gen}/lat_cost/lat_cost_y_0_hess.c',
]

build_files = [f'{gen}/acados_solver_lat.c'] + casadi_model + casadi_cost_y + casadi_cost_e + casadi_cost_0

# extra generated files used to trigger a rebuild
generated_files = [
  f'{gen}/Makefile',

  f'{gen}/main_lat.c',
  f'{gen}/acados_solver_lat.h',

  f'{gen}/lat_model/lat_expl_vde_adj.c',

  f'{gen}/lat_model/lat_model.h',
  f'{gen}/lat_cost/lat_cost_y_fun.h',
  f'{gen}/lat_cost/lat_cost_y_e_fun.h',
  f'{gen}/lat_cost/lat_cost_y_0_fun.h',
] + build_files

lenv = env.Clone()
lenv.Clean(generated_files, Dir(gen))

lenv.Command(generated_files,
             ["lat_mpc.py"],
             f"cd {Dir('.').abspath} && python lat_mpc.py")

lenv["CFLAGS"].append("-DACADOS_WITH_QPOASES")
lenv["CXXFLAGS"].append("-DACADOS_WITH_QPOASES")
lenv["CCFLAGS"].append("-Wno-unused")
lenv["LINKFLAGS"].append("-Wl,--disable-new-dtags")
lenv.SharedLibrary(f"{gen}/acados_ocp_solver_lat",
                   build_files,
                   LIBS=['m', 'acados', 'hpipm', 'blasfeo', 'qpOASES_e'])
